package sync

import (
	"context"
	"ez/apps/core/auto/mc"
	core "ez/apps/core/document"
	"gitee.com/dreamwood/ez-go/ez"
	sync "gitee.com/dreamwood/ez-go/model-sync"
	"gitee.com/dreamwood/ez-go/ss"
)

func init() {
	ez.Subscribe(ez.EventAfterServerRun, func(v interface{}, ctx context.Context) {
		sync.RegCreateEvent(mc.UserEventAfterCreate, "User")
		sync.RegCreateEvent(mc.UserEventAfterUpdate, "User")
		sync.RegCreateEvent(mc.UserEventDelete, "User")
		ez.Try(sync.GetMS().SubInitNeed(func(in *sync.InitNeed) error {
			userFeedToInit(in)
			return nil
		}))
	})
}

func userFeedToInit(in *sync.InitNeed) {
	page := 1
	done := false
	crud := core.NewUserCrud()
	for !done {
		rows, e := crud.FindBy(ss.M{}, []string{"id"}, page, 100)
		if ez.Try(e) {
			done = true
			return
		}
		if len(rows) == 0 {
			done = true
		}
		for _, row := range rows {
			ez.Try(sync.GetMS().FeedToInitEvent(in, row))
		}
	}
	return
}
